package org.duang.logs.db.elasticsearch;

import java.util.Map;

import org.duang.kit.ObjectKit;
import org.duang.logs.db.DBAppenderBase;
import org.duang.logs.db.ToolUtils;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ThrowableProxy;

public class ElasticSearchAppender<ILoggingEvent> extends DBAppenderBase<XContentBuilder, ILoggingEvent> {

	private static final String ID_FIELD = "id";
	private static final String THREAD_NAME_FIELD = "threadName";
	private static final String LOGGER_NAME_FIELD = "loggerName";
	private static final String LEVEL_FIELD = "level";
	private static final String MESSAGE_FIELD = "message";
	private static final String FORMATTED_MESSAGE_FIELD = "formattedMessage";
	private static final String THROWABLE_PROXY_FIELD = "throwableProxy";
	private static final String TIMESTAMP_FIELD = "timeStamp";
	
	private static final String CLIENT_HOST= "clientHost";
	private static final String CLIENT_PORT = "clientPort";
	private static final String PRODUCT_CODE = "productCode";
	
	public ElasticSearchAppender() {
		super(ElasticSearchLogBackDBFactory.init());
	}
	@Override
	protected XContentBuilder toObject(ILoggingEvent event) {
		try {
			XContentBuilder contentBuilder  = XContentFactory.jsonBuilder().startObject();
			Map<String,Object> map = ObjectKit.getFieldMap(event);			
			contentBuilder.field(CLIENT_HOST,  ToolUtils.getLocalHost());
			contentBuilder.field(CLIENT_PORT, ToolUtils.getLocalPort());
			contentBuilder.field(PRODUCT_CODE, ToolUtils.getProductCode());
			
			contentBuilder.field(THREAD_NAME_FIELD, map.get(THREAD_NAME_FIELD));
			contentBuilder.field(LOGGER_NAME_FIELD, map.get(LOGGER_NAME_FIELD));
			contentBuilder.field(LEVEL_FIELD, ((Level)map.get(LEVEL_FIELD)).toString());
			contentBuilder.field(MESSAGE_FIELD, map.get(MESSAGE_FIELD));
			contentBuilder.field(TIMESTAMP_FIELD, ToolUtils.getDateTime((long)map.get(TIMESTAMP_FIELD)));
			if(map.get(THROWABLE_PROXY_FIELD) != null) {
				contentBuilder.field(THROWABLE_PROXY_FIELD,ToolUtils.getStackTraceAsString((Exception)((ThrowableProxy)map.get(THROWABLE_PROXY_FIELD)).getThrowable()));
			}
			return contentBuilder;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		
	}
}
